package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.XML
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiUnderwriteCallback*
 * @Description:官微-H5承保信息回写
 * @remak ：官微-H5承保信息回写
 * @author: TH*
 * @date 2023-12-27 11:11:00
 *
 */
class apiGwUnderwriteCallback implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGwUnderwriteCallback.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long starttime = System.currentTimeMillis();
        long endtime;
        String callBack = null;//初始化请求参数
        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        //获取接口调用方式及参数
        String GetMethod = httpServletRequest.getMethod();
        log.debug("[GetMethod]:" + GetMethod);
        String inData = "";
        if (GetMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数：]" + inData);

        }


        if (KHUtil.isNull(inData)) {
            callBack = """<?xml version="1.0" encoding="UTF-8"?><response><head><status>F</status><errCode>9999</errCode><errMsg>请求参数不能为空!</errMsg></head><body></body></response>""";

            String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'apiGwUnderwriteCallback',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

            jt.update(insertsql, inData.toString(), callBack.toString())

            return callBack.toString();
        }
        try {

            log.debug("[官微-H5承保信息回写调用请求参数：]" + inData);

            String xmljson = XML.toJSONObject(inData);
            log.debug("[官微-H5承保信息回写参数XML转换成json：]" + xmljson);



            JSONObject jsonObject = JSONObject.fromObject(xmljson);

            String requestJson = GetJV(jsonObject, "request");

            JSONObject requestjson = JSONObject.fromObject(requestJson);




            String bodyJson1 = GetJV(requestjson, "body");


            JSONObject bodyjson = JSONObject.fromObject(bodyJson1);

            String FULL_POLICY_NO = "";//大保单号

            //body 主体信息
            String orderNo = GetJV(bodyjson, "orderNo");//订单号
            String userCode = GetJV(bodyjson, "userCode");//用户代码
            String task_guid = GetJV(bodyjson, "extendId");//任务编号
            //vehicle 车辆信息
            String vehicleJson1 = GetJV(bodyjson, "vehicle");
            JSONObject vehiclejson = JSONObject.fromObject(vehicleJson1);
            String licenseno = GetJV(vehiclejson, "licenseno");//车牌号
            String runareacode = GetJV(vehiclejson, "runareacode");//行驶区域
            String singeindate = GetJV(vehiclejson, "singeindate");//注册登记日期
            String modelcode = GetJV(vehiclejson, "modelcode");//车辆品牌型号
            String frameno = GetJV(vehiclejson, "frameno");//车架号（17位）
            String engineno = GetJV(vehiclejson, "engineno");//发动机号
            String chgownerflag = GetJV(vehiclejson, "chgownerflag");//是否过户
            String transferdate = GetJV(vehiclejson, "transferdate");//过户日期
            String newenergyclauseflag = GetJV(vehiclejson, "newenergyclauseflag");
//新能源条款(1： 新能源条款 0: 20年机动车条款)


            //carOwner 车主信息
            String carOwnerJson1 = GetJV(bodyjson, "carOwner");
            JSONObject carOwnerjson = JSONObject.fromObject(carOwnerJson1);

            String name = GetJV(carOwnerjson, "name");//车主姓名
            String identifynumber = GetJV(carOwnerjson, "identifynumber");//车主身份证号
            //applicant 投保人信息投保人姓名
            String applicantJson1 = GetJV(bodyjson, "applicant");
            JSONObject applicantJson = JSONObject.fromObject(applicantJson1);
            String tbappliname = GetJV(applicantJson, "appliname");//投保人姓名
            String tbmobilephone = GetJV(applicantJson, "mobilephone");//投保人手机号
            String tbidentifynumber = GetJV(applicantJson, "identifynumber");//投保人身份证号
            String tbappliaddress = GetJV(applicantJson, "appliaddress");//投保人地址

            //insured 被保险人信息
            String insuredJson1 = GetJV(bodyjson, "insured");
            JSONObject insuredJson = JSONObject.fromObject(insuredJson1);

            String bbappliname = GetJV(insuredJson, "appliname");//被保险人姓名
            String bbmobilephone = GetJV(insuredJson, "mobilephone");//被保险人手机号
            String bbidentifynumber = GetJV(insuredJson, "identifynumber");//被保险人身份证号
            String bbappliaddress = GetJV(insuredJson, "appliaddress");//被保险人地址


            //itemKindBZ 交强险信息
            String itemKindBZjson1 = GetJV(bodyjson, "itemKindBZ");

            String jqsumpricetaxtotal="";
            String jqdiscount ="";
            String jqpolicyno = "";
            String jqproposalno = "";
            String jqstartdate = "";
            String jqenddate = "";
            String jqaccepttime = "";
              if(!KHUtil.isNull(itemKindBZjson1)){
                  JSONObject itemKindBZJson = JSONObject.fromObject(itemKindBZjson1);
                  jqsumpricetaxtotal = GetJV(itemKindBZJson, "sumpricetaxtotal");//	险别保费
                  jqdiscount = GetJV(itemKindBZJson, "discount");//签单折扣
                  jqpolicyno = GetJV(itemKindBZJson, "policyno");//保单号
                  jqproposalno = GetJV(itemKindBZJson, "proposalno");//	投保单号
                  jqstartdate = GetJV(itemKindBZJson, "startdate");//	保险起期
                  jqenddate = GetJV(itemKindBZJson, "enddate");//	保险止期
                  jqaccepttime = GetJV(itemKindBZJson, "accepttime");//	承保确认时间


              }
            String itemKindBSjson1 = GetJV(bodyjson, "itemKindBS");

             String sysumpricetaxtotal ="";
             String sydiscount = "";
             String sypolicyno = "";
             String syproposalno = "";
             String systartdate = "";
             String syenddate = "";
             String syaccepttime = "";


            //itemKindBS 商业险信
                     if (!KHUtil.isNull(itemKindBSjson1)){
                         JSONObject itemKindBSJson = JSONObject.fromObject(itemKindBSjson1);
                         sysumpricetaxtotal = GetJV(itemKindBSJson, "sumpricetaxtotal");//	险别保费
                         sydiscount = GetJV(itemKindBSJson, "discount");//签单折扣
                         sypolicyno = GetJV(itemKindBSJson, "policyno");//保单号
                         syproposalno = GetJV(itemKindBSJson, "proposalno");//	投保单号
                         systartdate = GetJV(itemKindBSJson, "startdate");//	保险起期
                         syenddate = GetJV(itemKindBSJson, "enddate");//	保险止期
                         syaccepttime = GetJV(itemKindBSJson, "accepttime");//	承保确认时间
            }



            // tax 价税信息.
            String taxjson1 = GetJV(bodyjson, "tax");
            String sumPayTax ="";
            String sumpricetaxtotal="";
            if (!KHUtil.isNull(taxjson1)){
                JSONObject taxJson = JSONObject.fromObject(taxjson1);
                 sumPayTax = GetJV(taxJson, "sumPayTax");//	车船税
                 sumpricetaxtotal = GetJV(taxJson, "sumpricetaxtotal");//总保费
            }




            //sales 销售信息

            String salesjson1 = GetJV(bodyjson, "sales");
            JSONObject salesJson = JSONObject.fromObject(salesjson1);
            String salesmanCode = GetJV(salesJson, "salesmanCode");//业务员工号
            String solutionCode = GetJV(salesJson, "solutionCode");//子协议号
            String outerUserCode = GetJV(salesJson, "uterUserCode");//寿险业务员工号


            log.debug("orderNo:" + orderNo + "extendId:" + task_guid + "userCode" + userCode);

            String dealmsg = KHUtil.isNullMSG("orderNo", orderNo) + KHUtil.isNullMSG("extendId", task_guid) + KHUtil.isNullMSG("userCode", userCode);



            if (!KHUtil.isNull(dealmsg)) {

                callBack = """
             <?xml version="1.0" encoding="UTF-8"?>
             <response>
             <head>
             <status>F</status>
             <errCode>9999</errCode>
             <errMsg>$dealmsg</errMsg>
             </head>
             <body></body>
             </response>
                         """;

                String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,
                               return_info,
                               send_time,
                               return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'apiGwUnderwriteCallback',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                jt.update(insertsql, inData.toString(), callBack.toString())

                return callBack.toString();
            }


            log.debug("**************************【官微-H5承保信息回写】开始处理表数据*****************************");

            //给大保单号赋值
            if (KHUtil.isNull(syproposalno)) {
                FULL_POLICY_NO = jqproposalno;
            } else if (KHUtil.isNull(jqproposalno)) {
                FULL_POLICY_NO = syproposalno;
            } else {
                FULL_POLICY_NO = syproposalno;
            }

            //更新wd_quotation_extend表
            String updateSql1 = '''
                            Update 
                            wd_quotation_extend
                            Set 
                            QUOTE_NO=?,
                            SY_ORDER_NO=?,
                            JQ_ORDER_NO=?,
                            PAY_STATUS='1',
                            POLICY_STATUS='1',
                            MODIFIEDDATE=sysdate,
                            SUMCOST=?,
                            FULL_POLICY_NO=?,
                            SY_STARTDATE=?,
                            SY_ENDDATE=?,
                            JQ_STARTDATE=?,
                            JQ_ENDDATE=?,
                            BIZ_COST=?,
                            JQX_COST=?,
                            CVTAX=?,
                            JQ_POLICYCODE=?,
                            SY_POLICYCODE=?,
                            sy_discount=?,
                            jq_discount=?,
                            accepttime =?
                             where TASK_GUID=?
                              ''';


            jt.update(updateSql1,
                    orderNo,
                    syproposalno,
                    jqproposalno ,
                    sumpricetaxtotal,
                    FULL_POLICY_NO,
                    systartdate,
                    syenddate,
                    jqstartdate,
                    jqenddate,
                    sysumpricetaxtotal,
                    jqsumpricetaxtotal,
                    sumPayTax,
                    jqpolicyno,
                    sypolicyno,
                    jqdiscount,
                    sydiscount,
                    syaccepttime,
                    task_guid);


            //更新车辆信息wd_vehicle表
            String updatesql2 = '''
                               Update wd_vehicle
                               Set 
                              FRAME_CODE=?,
                              MODELCODE=?,
                              IN_STARTDATE=?,
                              CAR_PLATE=?,
                              ENGINE_CODE=?,
                              RUN_AREA_NAME=?,
                              TRANSFER_FLAG=?,
                              TRANSFER_DATE=?,
                              NEWENERGYCLAUSEFLAG=?
                              WHERE TASK_GUID=?
                              ''';

            jt.update(updatesql2, frameno, modelcode, singeindate, licenseno, engineno, runareacode, chgownerflag, transferdate, newenergyclauseflag, task_guid);


            //更新车主信息表 Wd_Vehicle_Insured  01
            String updatesql3 = ''' 
                          update Wd_Vehicle_Insured Set
                               name=?,
                               CUSTOMER_ID=?
                              where TASK_GUID=? and INSURED_TYPE='01'
                          ''';

            jt.update(updatesql3, name, identifynumber, task_guid);


            //更新车主信息表 Wd_Vehicle_Insured  02
            String updatesql4 = ''' 
                          update Wd_Vehicle_Insured Set
                              name=?,
                              CUSTOMER_ID=?,
                              MOBILE=?,
                              ADDRESS=?
                              where TASK_GUID=? and INSURED_TYPE='02'
                          ''';

            jt.update(updatesql4, tbappliname, tbidentifynumber, tbmobilephone, tbappliaddress, task_guid);


            //更新车主信息表 Wd_Vehicle_Insured  03
            String updatesql5 = ''' 
                          update Wd_Vehicle_Insured Set
                              name=?,
                              CUSTOMER_ID=?,
                              MOBILE=?,
                              ADDRESS=?
                              where TASK_GUID=? and INSURED_TYPE='03'
                          ''';
            jt.update(updatesql5, bbappliname, bbidentifynumber, bbmobilephone, bbappliaddress, task_guid);


            //更新销售信息 sales
            String update6 = ''' 
                             Update wd_sales Set
                             salesmanCode=?,
                             solutionCode=?,
                             outerUserCode=?
                             where task_guid=?
                               ''';

            jt.update(update6, salesmanCode, solutionCode, outerUserCode, task_guid);



            log.debug("*********************************开始调用官微订单成交数据回传*******************************************");
            //初始化官微请求参数


            String waterNo = KHUtil.getRandomString(36);
            String gwjson = """{
    "clueId":"$task_guid",
    "waterNo":"$waterNo",
    "orderNo":"$orderNo",
    "bzPolicyNo":"$jqpolicyno",
    "bzAcceptDate":"$jqaccepttime",
    "bsPolicyNo":"$sypolicyno",
    "bsAcceptDate":"$syaccepttime",
    "sumInsured":"$sumpricetaxtotal"
}""";
            /**JSONObject gwjson =new JSONObject();
             gwjson.put("clueId",task_guid);
             gwjson.put("waterNo",KHUtil.getRandomString(36))
             gwjson.put("orderNo",orderNo);
             gwjson.put("bzPolicyNo",jqpolicyno);
             gwjson.put("bzAcceptDate",jqaccepttime);
             gwjson.put("bsAcceptDate",syaccepttime);
             gwjson.put("sumInsured",sumpricetaxtotal);
             **/
            log.debug("【官微】订单成交数据回传接口请求参数：" + gwjson.toString());

            String sql2 = "select WEBSERVICEURL From sysc_interface where WEBTYPE='GW_URL'";
            List<Map<String, Object>> groovyUrl = jt.queryForList(sql2)
            String geturl = groovyUrl.get(0).get("WEBSERVICEURL");

            String gwrequestpath = geturl.toString() + "/blue-scrm/breakpoint/cluedeal";

            log.debug("【官微-订单成交数据回传cluedeal】请求地址URL：" + gwrequestpath.toString());

            //设置请求表头
            Map<String, String> TokenParams = new HashMap<String, String>();
            TokenParams.put("Content-Type", "application/json");
            String gwponsebody = Util.doHttpPostUseHead(gwrequestpath.toString(), gwjson, "UTF-8", 20000, 0, TokenParams, "");


            log.debug("【官微-订单成交数据回传cluedeal】接口返回报文：" + gwponsebody.toString());

            String isbs = null;
            if (!KHUtil.isNull(gwponsebody)) {

                JSONObject gwponsebodyjson = JSONObject.fromObject(gwponsebody);
                if (GetJV(gwponsebodyjson, "code") == "200") {
                    log.debug("【官微-订单成交数据回传cluedeal】处理成功");
                    isbs = "1";
                    String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  '/blue-scrm/breakpoint/cluedeal',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                    jt.update(insertsql, gwjson.toString(), gwponsebody.toString());
                } else {
                    log.debug("【官微-订单成交数据回传cluedeal】处理失败");
                    isbs = "2";
                    String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  '/blue-scrm/breakpoint/cluedeal',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                    jt.update(insertsql, gwjson.toString(), gwponsebody.toString());
                }


            }


            if (isbs.equals("1")) {

                callBack = """<?xml version="1.0" encoding="UTF-8"?> <response> <head> <status>S</status> <errCode>0000</errCode> <errMsg>电销系统处理成功</errMsg> </head> <body></body> </response>""";


                String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'apiGwUnderwriteCallback',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                jt.update(insertsql, inData.toString(), callBack.toString())
            } else {

                callBack = """<?xml version="1.0" encoding="UTF-8"?><response><head><status>S</status><errCode>0000</errCode><errMsg>H5承保数据回写电销成功,但调用官微订单成交数据回传接口返回失败！$gwponsebody</errMsg></head><body></body></response>""";


                String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'apiGwUnderwriteCallback',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                jt.update(insertsql, inData.toString(), callBack.toString())


            }
        } catch (Exception e) {
            log.error("【官微-H5承保信息回写电销异常】：" + e.getMessage());
            String error = e.getMessage();
            callBack = """<?xml version="1.0" encoding="UTF-8"?><response><head><status>F</status><errCode>9999</errCode><errMsg>H5承保信息回写电销异常:$error</errMsg></head><body></body></response>""";

            String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'apiGwUnderwriteCallback',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

            jt.update(insertsql, inData.toString(), e.getMessage())

        }


        return callBack.toString();
    }

    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

}
